package com.wl.video.live.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.loopj.android.http.TextHttpResponseHandler;
import com.wl.video.live.AppContext;
import com.wl.video.live.R;
import com.wl.video.live.api.LiveAPI;
import com.wl.video.live.bean.ChannelBean;
import com.wl.video.live.entity.LiveLinkEntity;
import com.wl.video.live.utils.DialogHelp;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cz.msebera.android.httpclient.Header;

public class ShowActivity extends Activity {

    @Bind(R.id.main_show_path)
    protected EditText showPath;

    @Bind(R.id.main_show_code)
    protected EditText showCode;

    @Bind(R.id.main_start)
    protected Button mainStartBtn;

    private ConfigActivity.PublishParam publishParam = null;
    private MsgReceiver msgReceiver = null;

    ClipboardManager mClipboardManager;
    private ProgressDialog waitDialog;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show);
        ButterKnife.bind(this);
        publishParam = new ConfigActivity.PublishParam();

        msgReceiver = new MsgReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("LiveStreamingStopFinished");
        registerReceiver(msgReceiver, intentFilter);

        LiveLinkEntity liveLinkEntity = new LiveLinkEntity();
        liveLinkEntity.setDeviceId(AppContext.getInstance().getAppId());
        mClipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);

        String livePath = AppContext.getInstance().getProperty("live_play_path");
        String liveCode = AppContext.getInstance().getProperty("live_play_code");

        showPath.setText(livePath == null ? "" : livePath.trim());
        showCode.setText(liveCode == null ? "" : liveCode.trim());

//        LiveAPI.getLiveLink(liveLinkEntity,showHandler);
    }

    private final TextHttpResponseHandler showHandler = new TextHttpResponseHandler() {
        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            Toast.makeText(getApplication(), "获取直播频道失败，请重新尝试！", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, String responseString) {

        }
    };

    private final TextHttpResponseHandler genCodeHandler = new TextHttpResponseHandler() {
        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            Toast.makeText(getApplication(), "更新邀请码失败，请重新尝试！", Toast.LENGTH_LONG).show();
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, String responseString) {
            //获取直播推流地址，频道号，考虑记录在本地
            if (statusCode == 200) {
                StringBuilder builder = new StringBuilder();
                builder.append(responseString);
                String builder_BOM = jsonTokener(builder.toString());
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject = JSONObject.parseObject(builder_BOM);
                    String code = jsonObject.getString("success");
                    if (code.trim().equals("true")) {
                        String body = jsonObject.getString("data");
                        jsonObject = JSONObject.parseObject(body);
                        body = jsonObject.getString("channel");
                        ChannelBean channelBean = JSON.parseObject(body, ChannelBean.class);

                        String liveCode = channelBean.getInviteCode();
                        showCode.setText(liveCode == null ? "" : liveCode.trim());
                        AppContext.getInstance().setProperty("live_play_code", liveCode);

                    }
                } catch (Exception e) {
                    Toast.makeText(getApplication(), "更新邀请码失败，请重新尝试！", Toast.LENGTH_LONG).show();

                }
            } else {
                Toast.makeText(getApplication(), "更新邀请码失败，请重新尝试！", Toast.LENGTH_LONG).show();

            }


//            Intent intent = new Intent(ConfigActivity.this, LiveActivity.class);
//            intent.putExtra("data", publishParam);
//            startActivity(intent);

//            Intent intent = new Intent(ConfigActivity.this, ShowActivity.class);
//            startActivity(intent);
        }
    };

    @OnClick(R.id.main_show_copy)
    protected void copyLink() {

        String livePath = AppContext.getInstance().getProperty("live_play_path");
        String liveCode = AppContext.getInstance().getProperty("live_play_code");

        if (null == livePath || livePath.trim().length() == 0) {
            Toast.makeText(getApplication(), "观看地址不存在，请先创建直播后再分享！", Toast.LENGTH_LONG).show();
            return;
        }
        if (null == liveCode || liveCode.trim().length() == 0) {
            Toast.makeText(getApplication(), "邀请码不存在，请先创建直播后再分享！", Toast.LENGTH_LONG).show();
            return;
        }

        String copyValue = "观看地址:" + showPath.getText() + " ,邀请码:" + showCode.getText();
        ClipData clipData = ClipData.newPlainText("copy from demo", copyValue);
        mClipboardManager.setPrimaryClip(clipData);
        Toast.makeText(getApplication(), "直播观看地址复制成功！", Toast.LENGTH_LONG).show();

    }

    @OnClick(R.id.main_gen_code)
    protected void genCode() {
        String livePath = AppContext.getInstance().getProperty("live_play_path");
        String liveCode = AppContext.getInstance().getProperty("live_play_code");

        if (null == livePath || livePath.trim().length() == 0) {
            Toast.makeText(getApplication(), "观看地址不存在，请先创建直播后再更新邀请码！", Toast.LENGTH_LONG).show();
            return;
        }

        new AlertDialog.Builder(this)
                .setTitle("确认要更新邀请码？")//标题
                .setIcon(R.mipmap.ic_launcher)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String liveCode = AppContext.getInstance().getProperty("live_play_code");
                        String deviceId = AppContext.getInstance().getAppId();
                        LiveAPI.genCode(deviceId, liveCode, genCodeHandler);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .show();
    }

    @OnClick(R.id.iv_back)
    protected void back() {
//        Intent intent = new Intent(ShowActivity.this, MainActivity.class);
//        startActivity(intent);
        finish();
    }

    @OnClick(R.id.main_start)
    protected void startLive() {
//        LiveChannelEntity liveChannelEntity = new LiveChannelEntity();
//        liveChannelEntity.setDeviceId(AppContext.getInstance().getAppId());
//        LiveAPI.getLiveChannel(liveChannelEntity, channelHandler);

        String livePath = showPath.getText().toString();
        String liveCode = showCode.getText().toString();

//
        if (null == livePath || livePath.trim().length() == 0) {
            Toast.makeText(getApplication(), "观看地址不存在，请先创建直播后再开播！", Toast.LENGTH_LONG).show();
            return;
        }
        if (null == liveCode || liveCode.trim().length() == 0) {
            Toast.makeText(getApplication(), "邀请码不存在，请先创建直播后再开播！", Toast.LENGTH_LONG).show();
            return;
        }
        showDialog();
        LiveLinkEntity liveLinkEntity = new LiveLinkEntity();
        liveLinkEntity.setDeviceId(AppContext.getInstance().getAppId());
        //请求推流地址
        LiveAPI.getLiveLink(liveLinkEntity, channelHandler);


    }

    protected void showDialog() {
        if (waitDialog == null) {
            waitDialog = DialogHelp.getWaitDialog(this, getString(R.string.liveing));
        }
        waitDialog.setCancelable(false);
        waitDialog.setCanceledOnTouchOutside(false);
        waitDialog.show();
    }

    protected void hideDialog() {
        if (waitDialog != null) {
            waitDialog.dismiss();
        }
    }

    private final TextHttpResponseHandler channelHandler = new TextHttpResponseHandler() {
        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            hideDialog();
            Toast.makeText(getApplication(), "获取直播推流失败，请重新尝试！", Toast.LENGTH_LONG).show();

        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, String responseString) {
            hideDialog();
            //获取直播推流地址，频道号，考虑记录在本地
            if (statusCode == 200) {
                StringBuilder builder = new StringBuilder();
                builder.append(responseString);
                String builder_BOM = jsonTokener(builder.toString());
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject = JSONObject.parseObject(builder_BOM);
                    String code = jsonObject.getString("success");
                    if (code.trim().equals("true")) {
                        String body = jsonObject.getString("data");
                        jsonObject = JSONObject.parseObject(body);
                        body = jsonObject.getString("channel");
                        ChannelBean channelBean = JSON.parseObject(body, ChannelBean.class);
                        String pushUrl = channelBean.getPushUrl();
                        if (null == pushUrl || pushUrl.trim().length() == 0) {
                            Toast.makeText(getApplication(), "未到直播时段，获取直播推流失败！", Toast.LENGTH_LONG).show();
                        } else {
                            publishParam.pushUrl = channelBean.getPushUrl();

////                           YOU "rtmp://pa569d9b7.live.126.net/live/ab1e3c7101b14833846a0e74e627f3bf?wsSecret=5c59a2abc52a020d76de2475d30a10c1&wsTime=1546944247"
////                               "rtmp://pba00bf65.live.126.net/live/a8121b8bb0c04e24aeb9febc720a954d?wsSecret=9e25702244cf34e6a180ade6f377cca3&wsTime=1547023290"
////                           ME "rtmp://pa569d9b7.live.126.net/live/23e77b0b99dc4a84aaf951a43ed07e10?wsSecret=e1ffb35d920cdb37afbdef15de50bdce&wsTime=1547022459"
//                            publishParam.pushUrl="rtmp://pba00bf65.live.126.net/live/a8121b8bb0c04e24aeb9febc720a954d?wsSecret=9e25702244cf34e6a180ade6f377cca3&wsTime=1547023290";
                            Intent intent = new Intent(ShowActivity.this, LiveActivity.class);
                            intent.putExtra("data", publishParam);
                            startActivity(intent);
                        }
                    }else{
                        Toast.makeText(getApplication(), "未到直播时段，获取直播推流失败！", Toast.LENGTH_LONG).show();
                    }
                } catch (Exception e) {
                    Toast.makeText(getApplication(), "获取直播推流失败，请重新尝试！", Toast.LENGTH_LONG).show();

                }
            } else {
                Toast.makeText(getApplication(), "获取直播推流失败，请重新尝试！", Toast.LENGTH_LONG).show();

            }


//            Intent intent = new Intent(ConfigActivity.this, LiveActivity.class);
//            intent.putExtra("data", publishParam);
//            startActivity(intent);

//            Intent intent = new Intent(ConfigActivity.this, ShowActivity.class);
//            startActivity(intent);
        }
    };

    protected String jsonTokener(String in) {
        if (in != null && in.startsWith("\ufeff")) {
            in = in.substring(1);
        }
        return in;
    }

    //用于接收Service发送的消息
    public class MsgReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            int value = intent.getIntExtra("LiveStreamingStopFinished", 0);
            if (value == 1)//finished
            {
                mainStartBtn.setEnabled(true);
                mainStartBtn.setText("进入直播");
            } else//not yet finished
            {
                mainStartBtn.setEnabled(false);
                mainStartBtn.setText("直播停止中...");
            }
        }
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(msgReceiver);
        msgReceiver = null;
        super.onDestroy();
    }

}
